package plugins.order;

import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.cache.CacheFactory;
import kd.bos.cache.DistributeSessionlessCache;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.dataentity.serialization.SerializationUtils;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.sdk.plugin.Plugin;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

import static jdk.nashorn.internal.runtime.JSType.toNumber;
import static kd.bos.login.utils.LoginUtils.logger;
import static kd.bos.servicehelper.user.UserServiceHelper.cacheKey;

/**
 * 单据界面插件
 */

public class CreatOrder extends AbstractBillPlugIn implements Plugin {

    DistributeSessionlessCache cache = CacheFactory.getCommonCacheFactory().getDistributeSessionlessCache("customRegion");

    @Override
    public void afterCreateNewData(EventObject e) {

        // cache.remove("model");

        String sourceData = cache.get("selecteddishesdata"); // 从缓存中获取数据
        String merchantId = cache.get("orderedmerchantid"); // 获取商户ID
        String tagValue = cache.get("model"); // 获取标签值


        if( !(tagValue != null && "takeaway".equals(tagValue))) {
            // 如果不是外卖模式，隐藏相关字段
            this.getView().setVisible(false, "dcb4_delivery");
            this.getView().setVisible(false, "dcb4_address");
        } else {


            // 1. 查询dcb4_delivery单据列表
            String entityName = "dcb4_delivery";
            String selectFields = "id,dcb4_user.name"; // 只需获取ID和用户名
            DynamicObjectCollection deliveryList = QueryServiceHelper.query(
                    entityName,
                    selectFields,
                    new QFilter[0]  // 空过滤条件数组
            );

            // 2. 随机抽取一条记录
            if (!deliveryList.isEmpty()) {
                int randomIndex = new Random().nextInt(deliveryList.size());
                DynamicObject randomDelivery = deliveryList.get(randomIndex);

                // 3. 获取基础资料字段的name属性值
                String userName = randomDelivery.getString("dcb4_user.name");

                // 4. 赋值到当前表单的配送员字段
                this.getModel().setValue("dcb4_delivery", userName);
                this.getView().updateView("dcb4_delivery"); // 刷新前端显示
            }
            cache.remove("model");


        }



        if (sourceData != null && !sourceData.isEmpty()) {

            List<Map<String, Object>> cacheData = SerializationUtils.fromJsonString(sourceData, List.class);
            this.getModel().setValue("dcb4_merchant", cache.get("orderedmerchantid")); // 设置商户名

            // 动态创建单据体行并赋值
            String entryKey = "dcb4_purchased_dishes";

            // 先清空单据体所有行
            this.getModel().deleteEntryData(entryKey);

            // 创建新行
            int[] newRowIndexes = this.getModel().batchCreateNewEntryRow(entryKey, cacheData.size());

            // 获取当前系统时间
            Calendar now = Calendar.getInstance();
            int hour = now.get(Calendar.HOUR_OF_DAY);
            int minute = now.get(Calendar.MINUTE);

            boolean isAfter2PM = hour >= 14; // 14点即下午2点
            boolean isAfter7PM = hour >= 19; // 19点即晚上7点
            boolean isNoon = (hour == 10 && minute >= 45) || (hour == 11 && minute <= 15)
                          || (hour == 12 && minute >= 45) || (hour == 13 && minute <= 15);

            for (int i = 0; i < cacheData.size(); i++) {
                Map<String, Object> rowData = cacheData.get(i);
                int rowIndex = newRowIndexes[i];

                // 5. 添加字段值空值检查
                Object dishesID = rowData.get("dishesID");
                Object dishPrice = rowData.get("price");

                if (dishesID != null) {
                    // 加载基础资料数据包
                    DynamicObject dishesObj = BusinessDataServiceHelper.loadSingle(dishesID, "dcb4_dishes");

                    // 赋值基础资料字段
                    this.getModel().setValue("dcb4_dishes", dishesObj, rowIndex);

                    // 获取基础资料的 name 属性并赋值给文本字段
                    String dishesName = dishesObj.getString("name");
                    this.getModel().setValue("dcb4_name", dishesName, rowIndex);
                }

                if (dishPrice != null) {
                    this.getModel().setValue("dcb4_price", dishPrice, rowIndex);
                }

                // 新增：根据时间设置折扣字段
                if (isAfter7PM) {

                    // this.getView().showTipNotification("下午2点后提供折扣");

                    this.getModel().setValue("dcb4_discount", 20, rowIndex);
                } else if (isNoon) {
                    this.getModel().setValue("dcb4_discount", 10, rowIndex);
                } else {
                    this.getModel().setValue("dcb4_discount", 0, rowIndex); // 默认无折扣
                }

                // 设置默认数量为1
                // this.getModel().setValue("dcb4_amount", 1, rowIndex);

                // 新增：计算并设置总价
                // calculateAndSetSum(rowIndex);

                // 锁定折扣字段
                this.getView().setEnable(false, rowIndex, "dcb4_discount");

                // 锁定单价字段
                this.getView().setEnable(false, rowIndex, "dcb4_price");

                // 锁定价格字段
                this.getView().setEnable(false, rowIndex, "dcb4_sum");

                // 锁定菜品字段
                this.getView().setEnable(false, rowIndex, "dcb4_dishes");

            }

            // 刷新单据体显示
            this.getView().updateView(entryKey);

            // 清理缓存（可选）
            cache.remove("selecteddishesdata"); // 清除缓存中的值
            cache.remove("orderedmerchantid"); // 清除商户ID缓存

        } else {
            // 如果缓存中没有数据，正常打开单据页面
            super.afterCreateNewData(e);
        }
    }
}
